//
//  MSBaseViewController.swift
//  SwiftWeibo
//
//  Created by 牟松 on 16/8/1.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import UIKit

class MSBaseViewController: UIViewController {
    
    // 是否有用户登录
//    var userLogon = false
    // 刷新控件
    var refreshControl: UIRefreshControl?
    // tableview控件
    var tableview: UITableView?
    // 判断上拉条件
    var ispullUp = false
    // 设置访客视图的字典
    var setVisiterDic = [String: String]()
    
    
    
    lazy var visitorView = MSVisitorView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.screenWidth, height: UIScreen.main.screenHeight))
    /// 自定义navigationBar
    lazy var navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.screenWidth, height: 64))
    /// 自定义的navigationItem
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)
  
        setupUI()
        
        automaticallyAdjustsScrollViewInsets = false
        
        NotificationCenter.default.addObserver(self, selector: #selector(receiveUserLoginSuccessNotifiction), name: NSNotification.Name(rawValue: WBUserLoginSuccess), object: nil)
    
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 支持竖屏
    func supportedInterfaceOrientations(for window: UIWindow?) -> UIInterfaceOrientationMask{
        return .portrait
    }

    /// set方法
    override var title: String? {
        didSet{
            navItem.title = title
        }
    }
    
    //MARK: - 监听方法
    /// 接收到登录成功通知
    @objc private func receiveUserLoginSuccessNotifiction(n: Notification){
        
        print("==========\(receiveUserLoginSuccessNotifiction)")
        
        
        for subView in view.subviews {
            subView.removeFromSuperview()
        }
        
        setupUI()
        
        NotificationCenter.default.removeObserver(self)
    }

}

// MARK: - 按钮监听事件
extension MSBaseViewController {
    @objc private func goFocusButtonDidClick() {
        print("关注")
    }
    @objc func loginButtonDidClick() {
        print("登录")
        NotificationCenter.default.post(name: NSNotification.Name.init(WBUserShouldLoginNotification), object: "LoginButtonDidClick")
    }
    @objc func registButtonDidClick() {
        
        
    }
}
// MARK: - 加载数据
extension MSBaseViewController {
    func loadData() {
        // 当子类覆写改方法的时候，优先指向子类方法
        
        refreshControl?.endRefreshing() // 走到这里说明没有子类在加载数据
        
    }
}

// MARK: - 设置界面
extension MSBaseViewController {
    
    // 设置navigationBar
    func setupUI() {
        setupNavigationBar()
                
        
        MSAFNManage.shared.userLogin ? loadData() : ()
        
        MSAFNManage.shared.userLogin ? setupTableView() : setupVisitorView()
        
        
        
        
    }
    private func setupNavigationBar() {
        view.addSubview(navBar)
        
        navBar.items = [navItem]
        
        navBar.titleTextAttributes = [NSForegroundColorAttributeName: #colorLiteral(red: 0.431372549, green: 0.431372549, blue: 0.431372549, alpha: 1)]
    }
    // 添加tableView
    func setupTableView() {
        
        tableview = UITableView(frame: view.bounds)
        tableview?.delegate = self
        tableview?.dataSource = self
        view.insertSubview(tableview!, belowSubview: navBar)
        tableview?.contentInset = UIEdgeInsets(top: 64, left: 0, bottom:  tabBarController?.tabBar.bounds.height ?? 49, right: 0) // 缩进
//        tableview?.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
        
        tableview?.scrollIndicatorInsets = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0) // 滑动条的缩进
        
        // 添加refreshControl
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged) // 调用的loadData方法，若子类覆写则优先调用子类
        tableview?.addSubview(refreshControl!)
        
        
    }
    // 添加访客视图
    private func setupVisitorView() {
        
        view.insertSubview(visitorView, belowSubview: navBar)
        
        visitorView.visitorDetailDic = setVisiterDic
        visitorView.goFocusButton.addTarget(self, action: #selector(goFocusButtonDidClick), for: .touchUpInside)
        visitorView.loginButton.addTarget(self, action: #selector(loginButtonDidClick), for: .touchUpInside)
        visitorView.registButton.addTarget(self, action: #selector(registButtonDidClick), for: .touchUpInside)
    }
    
}

// MARK: - tableView代理和数据源代理
extension MSBaseViewController: UITableViewDelegate, UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    // 用于判断在什么地方自动进行上拉加载
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 判断上啦加载的逻辑有问题
        // 在最后一个section的最后一个row显示的时候进行加载
        let row = indexPath.row
        
        
        let sectionNumber = tableView.numberOfSections // section的数量
        let rowNumber = tableView.numberOfRows(inSection: sectionNumber - 1) // 最后一个section的row的数量
        
        
        if  row == rowNumber - 1 && !ispullUp {
            print("上拉刷新")
            ispullUp = true
            loadData()
        }
        
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 10
    }
}
